package com.desire.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-13 周三 15:42
 * @since 17
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyPageInterceptor implements Interceptor {
    public static void startPage(int c,int p){
        currpage = c;
        pagesize = p;
    }

    public static void startPage(int c){
        currpage = c;
    }

    public static int currpage = 1;
    public static int pagesize = 10;
    public static int recordcount = 0;
    public static int pagecount = 1;

    /**
     * 插件的核心处理方法
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //System.out.println("拦截器:intercept(Invocation invocation)");
        var sh = invocation.getTarget();
        var mh = SystemMetaObject.forObject(sh);
        var ms = (MappedStatement) mh.getValue("delegate.mappedStatement");
        String msid = ms.getId();
        if("SELECT".equalsIgnoreCase(ms.getSqlCommandType().toString())) {
            //取出方法名，结束为ByPage的方法，才开始使用插件
            if (msid.endsWith("ByPage")) {
                //var ph = (ParameterHandler) mh.getValue("delegate.parameterHandler");
                //var param = (Map<String, Object>) ph.getParameterObject();
                String sql = mh.getValue("delegate.boundSql.sql").toString().trim() + String.format(" limit %d,%d", currpage * pagesize - pagesize, pagesize);
                mh.setValue("delegate.boundSql.sql", sql);
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        //System.out.println("拦截器：plugin(Object target)");
        //固定的写法，第二个参数表示要代理的对象 this
        return Plugin.wrap(target, this);
    }

    /**
     * 要传给这个插件的配置信息
     *
     * @param p
     */
    @Override
    public void setProperties(Properties p) {
        //System.out.println("拦截器：setProperties(Properties p)");
        pagesize = Integer.parseInt(p.getOrDefault("pagesize", 15).toString());
        currpage = Integer.parseInt(p.getOrDefault("currpage", 1).toString());
        //System.out.println(this.pagesize);
    }
}
